#ifndef LOGMANAGER_H
#define LOGMANAGER_H

#include <QWidget>
#include <QSqlTableModel>
#include <QDateTime>
#include <QTimer>
#include <QMutex>

// 前向声明
class LogWorker;

namespace Ui {
class LogManager;
}

class LogManager : public QWidget
{
    Q_OBJECT

public:
    explicit LogManager(QWidget *parent = nullptr);
    ~LogManager();

    // 静态方法，供其他模块记录日志 - 现在是异步的
    static void logOperation(int userId, const QString& action, const QString& details = "",
                            const QString& ipAddress = "", const QString& userAgent = "");
    static void logSystem(const QString& action, const QString& details = "");
    static void logAlarm(int alarmId, const QString& alarmContent, int userId = -1, int deviceId = -1);
    static void logError(const QString& errorDetails, int userId = -1);

    void setCurrentUserRole(const QString &role);

    // 设置自动导出阈值
    void setAutoExportThreshold(int threshold);

    // 获取当前日志数量
    int getCurrentLogCount();

    // 静态清理方法 - 必须是public static
    static void cleanupLogWorker();

public slots:
    void refreshLogs();

signals:
    // 自动导出完成信号
    void autoExportCompleted(const QString& filePath, int exportedCount);

private slots:
    void onQueryButtonClicked();
    void onResetButtonClicked();
    void onClearLogsClicked();
    void onAutoRefreshToggled(bool checked);
    void onLogTypeChanged(int index);
    void onExportLogsClicked();

    // 异步日志相关槽函数
    void onLogWritten(int totalCount);
    void onAutoExportCompleted(const QString& filePath, int exportedCount);
    void onLogWorkerError(const QString& error);

private:
    Ui::LogManager *ui;
    QSqlTableModel *logModel;
    QTimer *refreshTimer;

    void setupUI();
    void setupModel();
    void setupConnections();
    void applyFilters();

    QString currentUserRole;
    void applyUserPermissions();

    bool exportLogsToTxt(const QString& filePath);

    // 静态日志工作线程
    static LogWorker* s_logWorker;
    static QMutex s_workerMutex;

    // 初始化静态日志工作线程
    static void initLogWorker();
};

#endif // LOGMANAGER_H
